import 'dart:async';
import 'dart:io';
import 'package:auto_route/annotations.dart';
import 'package:auto_route/auto_route.dart';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:distribution_mall_flutter/assets.dart';
import 'package:distribution_mall_flutter/constant/cf_constant.dart';
import 'package:distribution_mall_flutter/constant/constant.dart';
import 'package:distribution_mall_flutter/constant/image_constant.dart';
import 'package:distribution_mall_flutter/constant/point_constant.dart';
import 'package:distribution_mall_flutter/dialog/down_hint_dialog.dart';
import 'package:distribution_mall_flutter/entity/goods/list/goods_list_entity.dart';
import 'package:distribution_mall_flutter/generated/l10n.dart';
import 'package:distribution_mall_flutter/main.dart';
import 'package:distribution_mall_flutter/mixins/page_stay_time.dart';
import 'package:distribution_mall_flutter/pages/home/application/home_service.dart';
import 'package:distribution_mall_flutter/pages/home/home_provider.dart';
import 'package:distribution_mall_flutter/pages/home/widgets/banner.dart';
import 'package:distribution_mall_flutter/pages/home/widgets/float_login.dart';
import 'package:distribution_mall_flutter/pages/home/widgets/home_goods/home_goods.dart';
import 'package:distribution_mall_flutter/pages/home/widgets/home_goods/home_goods_provider.dart';
import 'package:distribution_mall_flutter/pages/home/widgets/logistics.dart';
import 'package:distribution_mall_flutter/pages/home/widgets/product_appbar.dart';
import 'package:distribution_mall_flutter/pages/home/widgets/side_drawer.dart';
import 'package:distribution_mall_flutter/pages/home/widgets/tab.dart';
import 'package:distribution_mall_flutter/provider/common/article.dart';
import 'package:distribution_mall_flutter/provider/common/tab.dart';
import 'package:distribution_mall_flutter/provider/home/home.dart';
import 'package:distribution_mall_flutter/provider/home/waterfall.dart';
import 'package:distribution_mall_flutter/provider/order/order.dart';
import 'package:distribution_mall_flutter/provider/user/login.dart';
import 'package:distribution_mall_flutter/router/router.dart';
import 'package:distribution_mall_flutter/utils/common_third.dart';
import 'package:distribution_mall_flutter/utils/debug.dart';
import 'package:distribution_mall_flutter/utils/firebase/firebase_analytics_utils.dart';
import 'package:distribution_mall_flutter/utils/get_it.dart';
import 'package:distribution_mall_flutter/utils/image_loader.dart';
import 'package:distribution_mall_flutter/router/router.gr.dart';
import 'package:distribution_mall_flutter/utils/storage.dart';
import 'package:distribution_mall_flutter/utils/web.dart';
import 'package:distribution_mall_flutter/widgets/easy_refresh.dart';
import 'package:distribution_mall_flutter/widgets/goods_item_card.dart';
import 'package:distribution_mall_flutter/widgets/icon_button.dart';
import 'package:distribution_mall_flutter/widgets/keep_alive_scroll.dart';
import 'package:distribution_mall_flutter/widgets/pop_scope_overlay.dart';
import 'package:distribution_mall_flutter/widgets/shimmer.dart';
import 'package:distribution_mall_flutter/widgets/tabview/ep_tab_bar_view.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:extended_image/extended_image.dart';
import 'package:extended_nested_scroll_view/extended_nested_scroll_view.dart';
import 'package:extended_sliver/extended_sliver.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:skeletonizer/skeletonizer.dart';
import 'package:visibility_detector/visibility_detector.dart';

import 'widgets/home_appbar.dart';

final GlobalKey<ScaffoldState> _homeKey = GlobalKey<ScaffoldState>();

bool isSlide = false;
int? slide;

_checkForUpdates(BuildContext context, WidgetRef ref) {
  // Check whether a patch is available to install.
  WidgetsBinding.instance.addPostFrameCallback((_) async {
    // final isUpdateAvailable =
    //     await shorebirdCodePush.isNewPatchAvailableForDownload();
    // // isUpdateAvailable

    final appInfoModal = ref.watch(appInfoProvider);
    if (appInfoModal.showVersionUpdate ||
        (appInfoModal.showPatchUpdate &&
            appInfoModal.data?.isSilently != true)) {
      SmartDialog.show(
          backDismiss: false,
          clickMaskDismiss: false,
          builder: (_) {
            return const DownHintDialog();
          });
    } else if (appInfoModal.showPatchUpdate &&
        appInfoModal.data?.isSilently == true) {
      shorebirdCodePush.downloadUpdateIfAvailable().then((_) {
        ref.read(homeServiceProvider).setPatchNumber();
        DebugConstant.runFatEnv(() {
          EPToast.showToast(S.current.update_successfully);
        });
      });
    }
  });
}

@RoutePage()
class HomePage extends ConsumerStatefulWidget {
  // final String? saleItemId;
  const HomePage({super.key});

  @override
  ConsumerState createState() => _HomePage();
}

class _HomePage extends ConsumerState<HomePage>
    with PageStayTime<HomePage>, TickerProviderStateMixin {
  bool isDownHint = false;
  late StreamSubscription<List<ConnectivityResult>> subscription;
  bool isFirst = true;
  late final TabController homeTabController;
  @override
  String pageStayName = RouteInfoEnum.home.routeZhName;
  @override
  Map<String, Object?> pageStayMap = {};
  bool isFirstIos = !kIsWeb &&
      Platform.isIOS &&
      EPstorage.userInfo.get(UserInfoBoxKey.isFirst, defaultValue: true);

  @override
  void initState() {
    super.initState();
    homeTabController =
        TabController(length: tabName.length, vsync: this, initialIndex: 0);
    homeTabController.addListener(() {
      if (homeTabController.previousIndex != homeTabController.index) {
        FirebaseAnalyticsUtils.logEvent(
            name: '${RouteInfoEnum.home.routeZhName}访问',
            parameters: {
              'pageName': RouteInfoEnum.home.routeZhName,
              'stayTime': DateTime.now().difference(startTime).inSeconds,
              'tag': tabName[homeTabController.previousIndex]
            });
        pageStayMap['tag'] = tabName[homeTabController.index];
        startTime = DateTime.now();
      }
    });

    subscription = Connectivity()
        .onConnectivityChanged
        .listen((List<ConnectivityResult> result) {
      bool isFirst =
          EPstorage.userInfo.get(UserInfoBoxKey.isFirst, defaultValue: true);
      if (!kIsWeb &&
              Platform.isIOS &&
              isFirst &&
              result.contains(ConnectivityResult.wifi) ||
          result.contains(ConnectivityResult.mobile)) {
        isFirstIos = false;
        setState(() {});
        EPstorage.userInfo.put(UserInfoBoxKey.isFirst, false);
        ref.read(articleProvider.notifier).getProtocol();
        GetIt.initCommonHttp();
        ref.read(homeProvider.notifier).getBanner();
      }
    });
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      Future.delayed(const Duration(seconds: 1), () {
        // 协议
        ref.read(articleProvider.notifier).getProtocol();
      });
    });

    // 判断是否是通过h5链接的商品详情跳转过来的
    String? saleItemId = EPstorage.route.get(RouteBoxKey.isH5PDetail);
    if (saleItemId != null && saleItemId != '') {
      EPstorage.route.put(RouteBoxKey.isH5PDetail, null);
      appRouter.push(ProductDetailsRoute(saleItemId: saleItemId));
    }

    //第一帧过后
    DebugConstant.runEnvFlag('zry', () {
      WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
        // appRouter.push(LoginInviteCodeRoute());
      });
    });
  }

  @override
  popNextCallBack() {
    if (ref.read(loginStateProvider)) {
      getIt<WidgetRef>().watch(orderProvider.notifier).getOrderTrce();
    }
  }

  @override
  pushNextCallBack() {
    var tag = tabName[homeTabController.index];
    Map<String, Map<String, String>?> goodStayTime =
        ref.watch(homeGoodsStayProvider.select((item) => item.goodStayTime));
    FirebaseAnalyticsUtils.logEvent(
        name: PointConstant.hpGoodsExposure,
        parameters: {
          'list': goodStayTime.entries
              .where((item) => item.value?['time'] != null)
              .map((item) => {
                    'saleItemId': item.key,
                    'tag': item.value?['tag'],
                    'exposure_duration': item.value?['time']
                  })
              .toString()
        });
    ref.read(homeGoodsStayProvider.notifier).clearGoodStayTime();
    // 埋点用，页面被覆盖后，上报信息
    double pixels =
        ref.watch(waterfallProvider).scrollController?.position.pixels ?? 0;
    double height = EPstorage.deviceInfo.get(DeviceInfoBoxKey.height);
    if (!(pixels > 0)) return;
    FirebaseAnalyticsUtils.logEvent(
        name: PointConstant.hpPageScroll,
        parameters: {
          'pageScrollTop': pixels,
          'pageScrollScreenNum': pixels / height,
          'pageScreenHeight': height,
          'tag': tag,
          'number_of_goods': ref.read(homeGoodsProvider(tag)).data.length
        });
  }

  @override
  Widget build(BuildContext context) {
    ref.watch(articleProvider.notifier);
    ref.watch(homeServiceProvider);
    ref.watch(orderProvider);
    // double iscrollPxsTab =
    //     ref.watch(waterfallProvider.select((value) => value.scrollPx));
    bool firstLoading =
        ref.watch(waterfallProvider.select((value) => value.firstLoading));
    final waterModal = ref.watch(waterfallProvider);

    ref.listen(appInfoProvider, (pre, next) {
      if (pre?.data != next.data && next.data != null) {
        if (!isDownHint && !kIsWeb) {
          isDownHint = true;
          _checkForUpdates(context, ref);
        }
      }
    });

    return PopScopeOverlay(
      child: EPShimmer(
        enabled: firstLoading,
        // enabled: true,
        child: Scaffold(
          key: _homeKey,
          backgroundColor: Colors.white,
          appBar: HomeAppbar(context: context),
          endDrawer: const SideDrawer(),
          body: EasyRefresh.builder(
              header: defaultRefreshHeader(
                position: IndicatorPosition.locator,
              ),
              footer: defaultRefreshFooter(position: IndicatorPosition.locator),
              onRefresh: () async {
                var tag = tabName[homeTabController.index];
                await ref
                    .read(homeGoodsProvider(tag).notifier)
                    .refreshData(tag);
              },
              onLoad: () async {
                var tag = tabName[homeTabController.index];
                return await ref
                    .read(homeGoodsProvider(tag).notifier)
                    .onLoadMore(tag);
              },
              childBuilder: (context, physics) {
                return ScrollConfiguration(
                  behavior: const ERScrollBehavior(),
                  child: ExtendedNestedScrollView(
                    physics: physics,
                    controller: waterModal.scrollController,
                    onlyOneScrollInBody: true,
                    pinnedHeaderSliverHeightBuilder: () {
                      return MediaQuery.of(context).padding.top +
                          kToolbarHeight +
                          50;
                    },
                    headerSliverBuilder: (context, innerBoxIsScrolled) {
                      return [
                        SliverToBoxAdapter(
                            child: VisibilityDetector(
                          key: const Key('home_top'),
                          onVisibilityChanged: (VisibilityInfo visibilityInfo) {
                            ref
                                .read(homeIsTabProvider.notifier)
                                .setVisibilityInfo(visibilityInfo);
                          },
                          child: const Column(
                            children: [BannerInfoWidget(), Logistics()],
                          ),
                        )),
                        // ProductAppbar(homeTabController),
                        SliverPinnedToBoxAdapter(
                          child: Skeleton.ignore(
                            child: Consumer(
                              builder: (BuildContext context, WidgetRef ref,
                                  Widget? child) {
                                var isTab = ref.watch(homeIsTabProvider);
                                return Container(
                                  color: isTab == true
                                      ? Colors.white
                                      : const Color(0xFFF5F6F8), // AppBar的颜色
                                  child: Column(
                                    children: [
                                      HomeTab(
                                        wrapperHeight: 92.8,
                                        homeTabController: homeTabController,
                                      ),
                                      Container(
                                          width: double.infinity,
                                          height: 16,
                                          color: Colors.white)
                                    ],
                                  ),
                                );
                              },
                            ),
                          ),
                        ),
                        const HeaderLocator.sliver(clearExtent: false)
                      ];
                    },
                    body: EPTabBarView(
                      controller: homeTabController,
                      cacheExtent: (tabName.length / 2).round().toDouble(),
                      children: isFirstIos
                          ? []
                          : tabName
                              .map((e) => ExtendedVisibilityDetector(
                                  uniqueKey: Key(e),
                                  child: EPKeepAliveScrollWidget(
                                      child: HomeGoodsWidget(
                                          homeTabController: homeTabController,
                                          tag: e,
                                          physics: physics))))
                              .toList(),
                    ),
                  ),
                );
              }),
          floatingActionButtonLocation:
              FloatingActionButtonLocation.centerFloat,
          floatingActionButton: Container(
            width: double.infinity,
            margin: const EdgeInsets.only(
                left: EdgeConstant.edge146,
                right: EdgeConstant.edge146,
                bottom: 20),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.end,
              mainAxisSize: MainAxisSize.min,
              children: [
                Consumer(builder: (context, ref, _) {
                  bool isTab = ref.watch(homeIsTabProvider);
                  // var showFloatBtn =
                  //     ref.watch(waterfallProvider.select((e) => e.showFloatBtn));
                  return AnimatedOpacity(
                    opacity: isTab ? 0 : 1,
                    duration: const Duration(milliseconds: 500),
                    // 动画持续时间
                    child: SizedBox(
                      width: 42,
                      height: 42,
                      child: GestureDetector(
                        onTap: () {
                          if (!isTab) {
                            ref.read(waterfallProvider.notifier).onTop();
                          }
                        },
                        child: Container(
                          decoration: BoxDecoration(
                            shape: BoxShape.circle,
                            color: Colors.white.withOpacity(0.8),
                            boxShadow: const [
                              BoxShadow(
                                color: Color(0x0A000000),
                                offset: Offset(0, 4),
                                blurRadius: 4,
                              )
                            ],
                          ),
                          padding: const EdgeInsets.all(6),
                          child: ExtendedImage.network(
                            ImageConstant.homeToTopArrow,
                            width: 30,
                            enableLoadState: false,
                          ),
                        ),
                      ),
                    ),
                  );
                }),
                Container(
                  margin: const EdgeInsets.only(top: 15),
                  child: Consumer(
                    builder:
                        (BuildContext context, WidgetRef ref, Widget? child) {
                      return ref.watch(loginStateProvider)
                          ? Container()
                          : const FloatLogin();
                    },
                  ),
                )
              ],
            ),
          ),
        ),
      ),
    );
  }
}
